/**
 * Sensor Network Development Kit for 1-Wire Network (SeN)
 * Version : 0.1
 * Revision date : 2008-10-13
 * Author: Dubravko Penezic, dpenezic@gmail.com
 */

package owExample;



import java.util.Date;
import java.util.Enumeration;
import java.io.*;

import com.dalsemi.onewire.*;
import com.dalsemi.onewire.adapter.*;
import com.dalsemi.onewire.container.*;
import owLib.*;

/**
 * BasicSearchForDevice class do some basic search over communication adapter without activating hub/coupler 
 * Version : 0.1.1
 * Revision date : 2008-10-13
 * 
 * @author Dubravko Penezic, dpenezic@gmail.com
 *
 * Based on T. Bitson, SimpleWeather, SimpleWeather.java, 2007
 */
public class BasicSearchForDevice
{
  
  private DSPortAdapter adapter;
  private static OWConf c;
  private OneWireContainer owd;
  
/**
 *  Finding and init communication adapter and reset 1-Wire bus 
 */
  public BasicSearchForDevice()
  {
    try
    {
      adapter = OneWireAccessProvider.getAdapter(c.ONE_WIRE_ADAPTER_TYPE, c.ONE_WIRE_SERIAL_PORT);

      if (adapter != null)
      {
        System.out.println("Found Adapter: " + adapter.getAdapterName() +
                " on Port " + adapter.getPortName());
      }
      else
      {
        System.out.println("Error: Unable to find 1-Wire adapter!");
        System.exit(1);
      }

      resetBus();
    }
    catch (OneWireException e)
    {
      System.out.println("Error Finding Adapter: "+ e);
      System.exit(1);
    }
    
  }
  
/**
 * mainLoop is thread service , do loop checking if minute is change
 */
  public void mainLoop()
  {
    Date date = new Date();
    int minute, lastMinute = -99;
    boolean quit = false;
    InputStreamReader in = new InputStreamReader(System.in);
    
    
    // main program loop
    while(!quit)
    {
      try
      {
        Thread.sleep(1000);
      }
      catch (InterruptedException e)
      {}
      
      // check current time
      date.setTime(System.currentTimeMillis());
      minute = date.getMinutes();
       
      // only loop if a minute is change
      if (minute != lastMinute)
      {
        System.out.println("Time = " + date);
        
        try
        {

           adapter.beginExclusive(true);

           // clear any previous search restrictions
           adapter.setSearchAllDevices();
           adapter.targetAllFamilies();
           adapter.setSpeed(adapter.SPEED_REGULAR);

           // enumerate through all the 1-Wire devices found
           for (Enumeration owd_enum = adapter.getAllDeviceContainers();
                   owd_enum.hasMoreElements(); )
           {
              owd = ( OneWireContainer ) owd_enum.nextElement();

              System.out.println(owd.getAddressAsString()+" -> "+owd.getName()+" ("+owd.getAlternateNames()+")");
           }

           // end exclusive use of adapter
           adapter.endExclusive();

        }
        catch (Exception e)
        {
           System.out.println(e);
        }
        
        System.out.println("\n");
        
        // update the time
        lastMinute = minute;
      }
      
      // development use only - check for 'q' key press
      try
      {
        if (in.ready())
          if (in.read() == 'q')
          {
            quit = true;
        
            try
            {
              adapter.freePort();
            }
            catch (OneWireException e)
            {
              System.out.println("Error Finding Adapter: "+ e);
            }
			   }
      }
      catch (IOException e)
      { } 
    }
  }
  
/**
 * main start main program and test input parameters if exist, start thread service
 *    
 * @param args
 */
  public static void main(String[] args)
  {
    System.out.println("Starting " + c.VERSION);
    
    if (args.length != 0)
    {
      if (args[0].equals("-d"))
      {
        System.out.println("debug on");
        c.debugFlag = true;
      }
    }
    
    try
    {
      BasicSearchForDevice loopServer   = new BasicSearchForDevice();
      
      // call the main program loop
      loopServer.mainLoop();
    }
    catch(Throwable t)
    {
      System.out.println("Exception: Main() " + t);
    }
    finally
    {
      System.out.println(c.VERSION+" Stopped");
      System.exit(0);
    }
  }
  
/**
 * resetBus method try to reset 1-Wire bus
 *     
 */
  private void resetBus() 
  {
    System.out.println("Resetting 1-wire bus");
    
    try
    {
      int result = adapter.reset();
      
      if (result == 0)
        System.out.println("Warning: Reset indicates no Device Present");
      if (result == 3)
        System.out.println("Warning: Reset indicates 1-Wire bus is shorted");
    }
    catch (OneWireException e)
    {
      System.out.println("Exception Resetting the bus: " + e);
    }
  }
}
